package com.tema.controller;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.tema.entities.CompanyRelation;
import com.tema.entities.Job;
import com.tema.entities.User;
import com.tema.mapper.CompanyMapper;
import com.tema.mapper.JobMapper;
import com.tema.mapper.UserMapper;

import java.security.GeneralSecurityException;
import java.util.Properties;

@Controller
@RequestMapping("/login")
public class LoginController {
	@Autowired
	UserMapper userMapper;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	JobMapper jobMapper;
	
	@GetMapping
	public String toLogin() {
		return "login";
	}
	@PostMapping
	public String login(@RequestParam("userEmail") String email,
						@RequestParam("password") String password,
						HttpSession session, Model model) {
		User loginUser = userMapper.getOneByEmail(email);
		//数据加密
		String md5Passward = DigestUtils.md5DigestAsHex(password.getBytes());
		if (loginUser != null && loginUser.getPassword().equals(md5Passward)){
			loginUser = getUser(loginUser.getId());
			System.out.println(loginUser.getIsHR());
			session.removeAttribute("loginUser");
			session.setAttribute("loginUser", loginUser);
			if (email.equals("admin@admin.com")) {
				return "redirect:manager";
			}
			if (loginUser.getCompany() == null) {
				return "redirect:jobs";
			}
			return "redirect:home";
		}
		else {
			return "index";
		}
	}
	
	public User getUser(int userId) {
		User returnUser = userMapper.getOne(userId);
		returnUser.setCompany( companyMapper.getJobCompany(returnUser.getId()) );
		Job job = jobMapper.getUserJob(userId);
		returnUser.setJob(job);
		CompanyRelation companyRelation = userMapper.getCompany(userId);
		if (companyRelation != null && companyRelation.getCompanyId() != -1) {
			returnUser.setCompany(companyMapper.getCompany(companyRelation.getCompanyId()));
			returnUser.setIsAdmin(companyRelation.getIsAdmin());
			returnUser.setIsHR(companyRelation.getIsHR());
		}else {
			returnUser.setCompany(null);
			returnUser.setIsAdmin(false);
			returnUser.setIsHR(false);
		}
		return returnUser;
	}
	public void sendMail(String email) throws GeneralSecurityException {
		//reviser and sender
		String to = email;
		String from = "qin7899@qq.com";
		//here is host of mail, I use QQ mail
		String host = "smtp.qq.com";
		Properties properties = System.getProperties();
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth","true");
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", sf);

		Session session = Session.getInstance(properties,new Authenticator(){
			@Override
			public PasswordAuthentication getPasswordAuthentication()
			{
				//user and password, remember: DO NOT PUSH PASSWORD TO GITHUB!!!! by zzp
				return new PasswordAuthentication("qin7899@qq.com", "eksvzxpghznddhgc"); //发件人邮件用户名、授权码
			}
		});

		try {
			//create a message to send HTML doc
			MimeMessage message = new MimeMessage(session);

			message.setFrom(new InternetAddress(from));

			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			message.setSubject("打工人之家通知!");
			//insert captcha here
			String htmlText =
					"    <table class=\"body\" width=\"100%\" style=\"background-color:#757070d5; min-width:600px\" bgcolor=\"#757070d5\">\r\n" +
							"        <tr>\r\n" +
							"        <td class=\"body\" align=\"center\" valign=\"top\" width=\"100%\" style=\"min-width:600px\">\r\n" +
							"        <center>\r\n" +
							"        <table width=\"100%\" style=\"min-width:600px;\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"body\">\r\n" +
							"        <tr>\r\n" +
							"        <td align=\"center\">\r\n" +
							"        <table width=\"560\" class=\"panel-padded\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"min-width:560px\">\r\n" +
							"        <tr height=\"50\">\r\n" +
							"        <td width=\"100%\" height=\"50\" style=\"line-height:1px; font-size:1px\"> </td>\r\n" +
							"        </tr>\r\n" +
							"\r\n" +
							"        <tr>\r\n" +
							"        <td width=\"560\" align=\"center\" style=\"font-family:arial,helvetica,sans-serif; font-weight:bold; mso-line-height-rule: exactly; font-size:40px; color:#313131; text-align:left; line-height:75px\">\r\n" +
							"        <div style=\"text-align:center;line-height:70px\">您未进行能力测试，请尽快测试<br/>若您不需要，请忽略此邮件</div>\r\n" +
							"        </td>\r\n" +
							"        </tr>\r\n" +
							"\r\n" +
							"        <tr height=\"30\">\r\n" +
							"            <td width=\"100%\" height=\"30\" style=\"line-height:1px; font-size:1px\"> </td>\r\n" +
							"            </tr>\r\n" +
							"            </table>\r\n" +
							"            </td>\r\n" +
							"        </tr>\r\n" +
							"\r\n" +
							"        <tr>\r\n" +
							"            <td width=\"560\" align=\"center\" bgcolor=\"#000000\"; style=\"font-family:arial,helvetica,sans-serif; font-weight:bold; font-size:50px; color:#313131; text-align:left; line-height:75px\">\r\n" +
							"                <div  style=\"text-align:center; line-height:70px;color:  #c9aa71;\"><i>测试地址:<a href=\"https://www.nowcoder.com/mockexam/MockExam\"/></i></div>\r\n" +
							"            </td>\r\n" +
							"        </tr>\r\n" +
							"        <tr>\r\n" +
							"            <td align=\"center\">\r\n" +
							"            <table width=\"560\" class=\"panel-padded\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"min-width:560px\">\r\n" +
							"            <tr height=\"50\">\r\n" +
							"            <td width=\"100%\" height=\"50\" style=\"line-height:1px; font-size:1px\"> </td>\r\n" +
							"        </tr>\r\n" +
							"        <tr>\r\n" +
							"            <td width=\"560\" align=\"center\" style=\"font-family:arial,helvetica,sans-serif; font-weight:bold; mso-line-height-rule: exactly; font-size: 35px; color:#313131; text-align:left; line-height:75px\">\r\n" +
							"            <div style=\"text-align:center;line-height:70px\">感谢使用打工人之家</div>\r\n" +
							"            </td>\r\n" +
							"        </tr>\r\n" +
							"        <tr>\r\n" +
							"            <td width=\"560\" align=\"center\" style=\"font-family:arial,helvetica,sans-serif; font-weight:bold; mso-line-height-rule: exactly; font-size: 20px; color:#313131; text-align:left; line-height:75px\">\r\n" +
							"            <div style=\"text-align:center;line-height:70px\"></div>\r\n" +
							"            </td>\r\n" +
							"        </tr>\r\n" +
							"        </table>\r\n" +
							"        </center>\r\n" +
							"    </td>\r\n" +
							"    </tr>\r\n" +
							"    </table>";

			message.setContent(htmlText, "text/html; charset=UTF-8");
			Transport.send(message);
			System.out.println("Sent message successfully");
		} catch (MessagingException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
